package api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import domain.User;
import service.UserService;
import utils.GetRequestJsonUtils;
import utils.Response;
import utils.ResponseCode;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;

public class RegisterServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        JSONObject object=null;
        Response build=null;
        User user=null;
        try {
            object = GetRequestJsonUtils.getRequestJsonObject(req);
            String userString=object.getString("user");
            user= JSON.parseObject(userString,User.class);
        }catch (Exception e){
            //e.printStackTrace();
            build=Response.build(ResponseCode.ERROR_PARAN);
            resp.setContentType("application/json;charset=utf-8");
            resp.getWriter().write(JSON.toJSON(build).toString());
            return;
        }

        UserService userService=new UserService();
        user.setActiveCode(UUID.randomUUID().toString());//生成一个随机数（不会重复），作为激活码写入数据库
        if(userService.register(user)){//注册成功
            build=Response.build(ResponseCode.SUCCESS,"您已经注册成功，快去登录邮箱激活账号！");
        }else {
            build=Response.build(ResponseCode.ERROR,"注册失败！");
        }
        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().write(JSON.toJSON(build).toString());
    }
}
